package com.lss.fmap.fragment;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcel;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.google.android.material.button.MaterialButton;
import com.google.android.material.datepicker.CalendarConstraints;
import com.google.android.material.datepicker.MaterialDatePicker;
import com.google.android.material.snackbar.Snackbar;
import com.lss.fmap.R;

import java.util.Calendar;
import java.util.List;
import java.util.Locale;


public class AccountFragment extends Fragment implements View.OnClickListener {

    private LinearLayout incomeContainer;
    private LinearLayout expenseContainer;
    private int currentSelectedType = EXPENSE; // 默认选中收入

    public static final int INCOME = 1;
    public static final int EXPENSE = 2;

    private static final String TAG = "AccountFragment";
    private static final String MONEY = "￥";
    private static final double MAX_AMOUNT = 9999;

    // 金额 TextView
    private TextView tvAmount;
    // 日期选择组件
    private Button btnPicker;
    private TextView tvIncome;
    private TextView tvExpense;
    private Calendar selectedCalendar = Calendar.getInstance();

    public AccountFragment() {
        // Required empty public constructor
    }

    public static AccountFragment newInstance(String param1, String param2) {
        AccountFragment fragment = new AccountFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_account, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        LinearLayout expenseIconsContainer = view.findViewById(R.id.expense_icons_container);
        LinearLayout paymentIconsContainer = view.findViewById(R.id.payment_icons_container);
        // 支出类型icon数据
        List<IconData> expenseIcons = List.of(
                new IconData(R.drawable.catering, "餐饮"),
                new IconData(R.drawable.shopping, "购物"),
                new IconData(R.drawable.traffic, "交通"),
                new IconData(R.drawable.service, "服务")
        );
        addIconsToContainer(expenseIconsContainer, expenseIcons, iconData -> Log.i(TAG, "onIconClick: " + iconData.label));
        // 收支类型icon数据
        List<IconData> paymentIcons = List.of(
                new IconData(R.drawable.zhifubao, "支付宝"),
                new IconData(R.drawable.vx, "微信"),
                new IconData(R.drawable.bankcard, "银行卡"),
                new IconData(R.drawable.cash, "现金")
        );
        addIconsToContainer(paymentIconsContainer, paymentIcons, iconData -> Log.i(TAG, "onIconClick: " + iconData.label));

        incomeContainer = view.findViewById(R.id.income_container);
        expenseContainer = view.findViewById(R.id.expense_container);
        // 月份选择按钮 & 收入 & 支出
        btnPicker = view.findViewById(R.id.btn_month_picker);
        tvIncome = view.findViewById(R.id.tv_total_income);
        tvExpense = view.findViewById(R.id.tv_total_expense);
        btnPicker.setOnClickListener(this);
        // 设置初始月份文本
        updateMonthText();

        // 设置初始选中状态
        expenseContainer.setSelected(true);

        // 设置点击监听器
        incomeContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectType(INCOME);
            }
        });

        expenseContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectType(EXPENSE);
            }
        });

        Log.i(TAG, "onViewCreated: " + "获取计算结果");
        // 初始化金额显示
        tvAmount = view.findViewById(R.id.tv_amount);
        String initValue = getString(R.string.init_value);
        tvAmount.setText(initValue);
        // 初始化数字键盘
        setupNumberKeyboard(view);
    }

    /**
     * 设置数字键盘事件处理
     */
    private void setupNumberKeyboard(View rootView) {
        View.OnClickListener numberClickListener = v -> {
            MaterialButton button = (MaterialButton) v;
            // 处理数字
            handleNumber(button.getText().toString());
        };
        // 获取特殊键
        rootView.findViewById(R.id.btn_clear).setOnClickListener(v -> {
            handleClear();
        });
        rootView.findViewById(R.id.btn_backspace).setOnClickListener(v -> {
            handleBackspace();
        });
        rootView.findViewById(R.id.btn_dot).setOnClickListener(v -> {
            handleDot();
        });
        rootView.findViewById(R.id.btn_done).setOnClickListener(v -> {
            handleDone();
        });

        // 注册所有数字按钮
        int[] numberButtonIds = {
                R.id.btn_0, R.id.btn_1, R.id.btn_2, R.id.btn_3,
                R.id.btn_4, R.id.btn_5, R.id.btn_6,
                R.id.btn_7, R.id.btn_8, R.id.btn_9
        };

        for (int id : numberButtonIds) {
            rootView.findViewById(id).setOnClickListener(numberClickListener);
        }
    }

    /**
     * 显示Toast消息
     */
    @SuppressLint("ResourceAsColor")
    private void showToast(String message) {
        View rootView = requireView();
        Snackbar.make(rootView, message, Snackbar.LENGTH_SHORT)
                .setAnimationMode(Snackbar.ANIMATION_MODE_SLIDE)
                .setBackgroundTint(Color.parseColor("#56d18b"))
                .setTextColor(R.color.dialog_text_color)
                .show();
    }

    /**
     * 处理 确认
     */
    private void handleDone() {
        String amountStr = tvAmount.getText().toString();
        String initValue = getString(R.string.init_value);

        // 确保金额不为初始值
        if (!amountStr.equals(initValue)) {
            try {
                // 去掉货币符号和逗号分隔符
                String cleanAmount = amountStr.replace(MONEY, "").replace(",", "");
                double amount = Double.parseDouble(cleanAmount);

                // 验证金额是否超过限制
                if (amount <= MAX_AMOUNT) {
                    // TODO: 实际完成逻辑，如保存记录等
                    Log.d(TAG, "完成金额输入: " + amount);
                    showToast("记账成功: " + amountStr);
                } else {
                    showToast("金额不能超过" + MAX_AMOUNT);
                }
            } catch (NumberFormatException e) {
                Log.e(TAG, "金额格式错误: " + amountStr);
                showToast("金额格式错误");
            }
        } else {
            showToast("金额不能为空");
        }
    }

    /**
     * 处理 点
     */
    private void handleDot() {
        String currentText = tvAmount.getText().toString();
        String cleanText = currentText.replace(MONEY, "").replace(",", "");

        // 确保当前金额已包含数字
        if (cleanText.equals("0")) {
            tvAmount.setText(MONEY + "0.");
            return;
        }

        // 禁止多个小数点
        if (!cleanText.contains(".")) {
            // 更新显示金额并格式化
            updateAmountDisplay(cleanText + ".");
        }
    }

    /**
     * 退格
     */
    private void handleBackspace() {
        String currentText = tvAmount.getText().toString();
        String cleanText = currentText.replace(MONEY, "").replace(",", "");
        String initValue = getString(R.string.init_value);

        // 至少保留一个字符
        if (cleanText.length() > 1) {
            String newValue = cleanText.substring(0, cleanText.length() - 1);
            updateAmountDisplay(newValue);
        } else {
            tvAmount.setText(initValue);
        }
    }

    /**
     * 清空
     */
    private void handleClear() {
        tvAmount.setText(getString(R.string.init_value));
    }

    /**
     * 处理数字
     *
     * @param digit 数字参数
     */
    private void handleNumber(String digit) {
        String currentText = tvAmount.getText().toString();
        String cleanText = currentText.replace(MONEY, "").replace(",", "");
        String initValue = getString(R.string.init_value);

        // 如果是初始值，直接替换
        if (cleanText.equals("0") || currentText.equals(initValue)) {
            updateAmountDisplay(digit);
            return;
        }

        // 检查小数点后的位数
        if (cleanText.contains(".")) {
            int decimalIndex = cleanText.indexOf(".");
            if (cleanText.length() - decimalIndex > 3) { // 最多两位小数
                showToast("最多输入两位小数");
                return;
            }
        }

        // 检查是否超过最大位数
        String digitsOnly = cleanText.replace(".", "");
        if (digitsOnly.length() >= 7) { // 最大10000.00是7位数字
            showToast("金额位数已达上限");
            return;
        }

        // 追加数字并更新显示
        String newValue = cleanText + digit;
        updateAmountDisplay(newValue);
    }

    /**
     * 更新金额显示（自动格式化为带逗号的金额）
     */
    private void updateAmountDisplay(String amount) {
        try {
            // 转换为数值类型
            double value = Double.parseDouble(amount);

            // 检查是否超过最大金额限制
            if (value > MAX_AMOUNT) {
                showToast("金额不能超过" + MAX_AMOUNT);
                return;
            }

            // 格式化金额（添加逗号分隔符）
            String formatted = formatAmount(amount);
            tvAmount.setText(MONEY + formatted);
        } catch (NumberFormatException e) {
            // 如果无法转换为数字（例如包含多个小数点），使用原始值
            tvAmount.setText(MONEY + amount);
        }
    }

    /**
     * 格式化金额（添加千分位逗号）
     */
    private String formatAmount(String amount) {
        // 分离整数和小数部分
        String[] parts = amount.split("\\.");
        String integerPart = parts[0];
        String decimalPart = parts.length > 1 ? parts[1] : "";

        // 确保小数部分最多两位
        if (decimalPart.length() > 2) {
            decimalPart = decimalPart.substring(0, 2);
        }

        // 格式化整数部分（添加逗号）
        StringBuilder formatted = new StringBuilder();
        int count = 0;
        for (int i = integerPart.length() - 1; i >= 0; i--) {
            formatted.insert(0, integerPart.charAt(i));
            count++;
            if (count % 3 == 0 && i > 0) {
                formatted.insert(0, ",");
            }
        }

        // 添加小数部分
        if (!decimalPart.isEmpty()) {
            formatted.append(".").append(decimalPart);
        } else if (amount.contains(".")) {
            formatted.append(".");
        }

        return formatted.toString();
    }
    private void selectType(int type) {
        if (currentSelectedType == type) return;

        currentSelectedType = type;

        switch (type) {
            case INCOME:
                incomeContainer.setSelected(true);
                expenseContainer.setSelected(false);
                // 执行收入相关逻辑
                break;
            case EXPENSE:
                incomeContainer.setSelected(false);
                expenseContainer.setSelected(true);
                // 执行支出相关逻辑
                break;
        }
    }

    @Override
    public void onClick(View v) {
        // 处理月份picker按钮点击事件
        if (v.getId() == R.id.btn_month_picker){
            Log.d(TAG, "onClick: 开始==================> picker点击事件");
            showMonthPickerDialog();
        }
    }
    /**
     * 显示月份选择对话框
     */
    @SuppressLint("MissingInflatedId")
    private void showMonthPickerDialog() {
        // 创建自定义的月份选择对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        View dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_month_picker, null);
        builder.setView(dialogView);

        // 初始化视图
         NumberPicker yearPicker = dialogView.findViewById(R.id.year_picker);
        NumberPicker monthPicker = dialogView.findViewById(R.id.month_picker);
        Button btnConfirm = dialogView.findViewById(R.id.btn_confirm);

        // 设置年份范围（当前年份前后5年）
        int currentYear = Calendar.getInstance().get(Calendar.YEAR);
        int minYear = currentYear - 5;
        int maxYear = currentYear + 5;

        // 设置年份选择器
        yearPicker.setMinValue(minYear);
        yearPicker.setMaxValue(maxYear);
        yearPicker.setValue(selectedCalendar.get(Calendar.YEAR));

        // 设置月份选择器
        monthPicker.setMinValue(1);
        monthPicker.setMaxValue(12);
        monthPicker.setValue(selectedCalendar.get(Calendar.MONTH) + 1);

        // 设置月份显示格式
        monthPicker.setDisplayedValues(new String[]{
                "1月", "2月", "3月", "4月", "5月", "6月",
                "7月", "8月", "9月", "10月", "11月", "12月"
        });

        // 创建对话框
        AlertDialog dialog = builder.create();
        if (dialog.getWindow() != null) {
            // 设置窗口背景为透明，这样圆角才能显示出来
            dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialog_window_bg);

            // 移除默认的背景
            dialog.getWindow().setDimAmount(0.5f); // 设置背景变暗程度
        }
        // 确认按钮点击事件
        btnConfirm.setOnClickListener(v -> {
            int selectedYear = yearPicker.getValue();
            int selectedMonth = monthPicker.getValue();

            // 更新选择的月份
            selectedCalendar.set(Calendar.YEAR, selectedYear);
            selectedCalendar.set(Calendar.MONTH, selectedMonth - 1);

            // 更新月份显示文本
            updateMonthText();

            // 刷新月度统计数据
            refreshMonthlySummary();

            // 关闭对话框
            dialog.dismiss();
        });

        // 显示对话框
        dialog.show();
    }
    /**
     * 显示月份选择对话框
     */
//    private void showMonthPickerDialog() {
//        Log.d(TAG, "onClick: 开始==================> showMonthPickerDialog");
//        // 创建Material3风格的日期选择器
//        MaterialDatePicker<Long> datePicker = MaterialDatePicker.Builder.datePicker()
//                .setTitleText("选择月份")
//                .setSelection(selectedCalendar.getTimeInMillis())
//                .setCalendarConstraints(limitToMonthSelection())
//                .build();
//
//        datePicker.addOnPositiveButtonClickListener(selection -> {
//            // 更新选择的月份
//            selectedCalendar.setTimeInMillis(selection);
//            updateMonthText();
//
//            // 刷新月度统计数据
//            refreshMonthlySummary();
//        });
//
//        // 显示对话框
//        datePicker.show(getParentFragmentManager(), "MONTH_PICKER");
//    }
    /**
     * 限制选择器只能选择月份（不能选择具体日期）
     */
    private CalendarConstraints limitToMonthSelection() {
        // 设置日期选择器只显示月份视图
        CalendarConstraints.Builder constraintsBuilder = new CalendarConstraints.Builder();
        constraintsBuilder.setValidator(new MonthValidator());

        // 设置日期范围（例如过去5年到未来1年）
        Calendar minDate = Calendar.getInstance();
        minDate.add(Calendar.YEAR, -5);

        Calendar maxDate = Calendar.getInstance();
        maxDate.add(Calendar.YEAR, 1);

        constraintsBuilder.setStart(minDate.getTimeInMillis());
        constraintsBuilder.setEnd(maxDate.getTimeInMillis());

        return constraintsBuilder.build();
    }

    /**
     * 更新月份显示文本
     */
    private void updateMonthText() {
        String monthText = String.format(Locale.getDefault(),
                "%d年%d月",
                selectedCalendar.get(Calendar.YEAR),
                selectedCalendar.get(Calendar.MONTH) + 1);

        btnPicker.setText(monthText);
    }
    /**
     * 刷新月度统计数据
     */
    private void refreshMonthlySummary() {
        // 这里应该从数据库或ViewModel获取数据
        int year = selectedCalendar.get(Calendar.YEAR);
        int month = selectedCalendar.get(Calendar.MONTH) + 1;

        // 模拟数据
        double totalExpense = 3285.75;
        double totalIncome = 12500.00;

        // 更新UI
        tvExpense.setText(String.format(Locale.getDefault(), "总支出: ￥%.2f", totalExpense));
        tvIncome.setText(String.format(Locale.getDefault(), "总收入: ￥%.2f", totalIncome));
    }

    /**
     * 自定义验证器，限制只能选择月份
     */
    @SuppressLint("ParcelCreator")
    private static class MonthValidator implements CalendarConstraints.DateValidator {
        @Override
        public boolean isValid(long date) {
            // 所有日期都有效，因为我们只关心月份
            return true;
        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            // 空实现
        }
    }
    // 图标点击监听器接口
    interface IconClickListener {
        void onIconClick(IconData iconData);
    }
    private void addIconsToContainer(LinearLayout container, List<IconData> icons, IconClickListener listener) {
        container.removeAllViews();

        float density = getResources().getDisplayMetrics().density;
        int itemWidth = (int)(60 * density);
        int itemHeight = LinearLayout.LayoutParams.WRAP_CONTENT;
        int marginRight = (int)(2 * density);

        for (IconData iconData : icons) {
            View itemView = LayoutInflater.from(getContext()).inflate(R.layout.item_icon, container, false);

            ImageView iconImage = itemView.findViewById(R.id.iv_icon);
            TextView iconLabel = itemView.findViewById(R.id.tv_label);

            iconImage.setImageResource(iconData.iconRes);
            iconLabel.setText(iconData.label);

            // 设置布局参数
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(itemWidth, itemHeight);
            params.setMargins(0, 0, marginRight, 0);
            itemView.setLayoutParams(params);

            // 设置点击效果
            itemView.setBackground(ContextCompat.getDrawable(requireContext(), R.drawable.bg_icon_selector));
            itemView.setOnClickListener(v -> {
                // 更新选中状态
                updateIconSelection(container, itemView);
                // 回调点击事件
                if (listener != null) {
                    listener.onIconClick(iconData);
                }
            });

            container.addView(itemView);
        }
    }

    private void updateIconSelection(LinearLayout container, View selectedView) {
        // 遍历容器中的所有子视图，更新选中状态
        for (int i = 0; i < container.getChildCount(); i++) {
            View child = container.getChildAt(i);
            boolean isSelected = child == selectedView;
            child.setAlpha(isSelected ? 1.0f : 0.6f);
        }
    }
    /**
     * 数据图标类
     */
    static class IconData {
        int iconRes;
        String label;

        IconData(int iconRes, String label) {
            this.iconRes = iconRes;
            this.label = label;
        }
    }
}